package tech.aistar.day10.visibility;

import java.io.File;

/**
 * 本类用来演示: 可见性
 *
 * @author: success
 * @date: 2022/8/1 2:46 下午
 */
public class VolatileDemo {

    //保证x具备可见性
    //如何做到"可见性" - write-x刷回主存 - 主存x发生变化 - read线程立即从主存拉取最新的x
    private volatile int x; // 主存x=0;

    //线程负责读
    public void read(){
        while(x!=5){
            //死循环...
            //System.out.println();

            //只要获取锁,先清空本地的工作内存,从主存中重新拉取最新的x
            //synchronized (this){
            //
            //}

            //睡一秒 - cpu空闲
            //try {
            //    Thread.sleep(1000);
            //} catch (InterruptedException e) {
            //    e.printStackTrace();
            //}

            //IO操作
            //File file = new File("src/tech/aistar/day01/HelloWorld.java");

            //Thread.yield();//线程的礼让,让出cpu执行时间片

        }
        if(x==5){
            System.out.println("read...");
        }
    }

    //线程负责写
    public void write(){
        //System.out.println("---");
        x=5;
    }
}
class VolatileDemoTest{
    public static void main(String[] args) {
        VolatileDemo v = new VolatileDemo();
        //1. 创建写的线程
        Thread t1 = new Thread(()->v.write());

        //2. 创建一个读的线程
        Thread t2 = new Thread(()->v.read());

        //先读
        t2.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //再写
        t1.start();
    }
}